<template>
  <div class="article-detail">
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <div>加载中...</div>
    </div>
    <div v-if="error" class="error">{{ error }}</div>
    
    <div v-if="!loading && article" class="article-content">
      <div class="article-header">
        <h1>{{ article.title }}</h1>
        <div class="article-meta">
          <span v-if="article.author" class="author">
            <i class="icon-user"></i> {{ article.author }}
          </span>
          <span v-if="article.publishTime" class="publish-time">
            <i class="icon-calendar"></i> {{ formatDate(article.publishTime) }}
          </span>
          <span class="view-count">
            <i class="icon-eye"></i> {{ article.viewCount || 0 }}次阅读
          </span>
        </div>
        <div v-if="article.tags" class="article-tags">
          <span v-for="(tag, index) in getTagArray(article.tags)" :key="index" class="tag">{{ tag }}</span>
        </div>
      </div>
      
      <div v-if="article.coverImage" class="article-cover">
        <img :src="getImageUrl(article.coverImage)" :alt="article.title">
      </div>
      
      <div class="article-body markdown-body" v-html="renderMarkdown(article.content)"></div>
      
      <div class="article-actions">
        <div class="action-buttons">
          <button class="btn btn-like" @click="handleLike" :class="{'liked': isLiked}">
            <i class="icon-heart"></i> {{ isLiked ? '已点赞' : '点赞' }} 
            <span class="count">{{ likeCount }}</span>
          </button>
          <button class="btn btn-share" @click="handleShare">
            <i class="icon-share"></i> 分享
          </button>
        </div>
        
        <router-link :to="'/article/list'" class="btn btn-back">返回列表</router-link>
      </div>
      
      <!-- 相关文章推荐 -->
      <div v-if="relatedArticles.length > 0" class="related-articles">
        <h3>相关文章推荐</h3>
        <ul class="related-list">
          <li v-for="relatedArticle in relatedArticles" :key="relatedArticle.id">
            <router-link :to="`/article/view/${relatedArticle.id}`">
              {{ relatedArticle.title }}
            </router-link>
            <span class="related-date">{{ formatDate(relatedArticle.publishTime) }}</span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { marked } from 'marked';
import DOMPurify from 'dompurify';

export default defineComponent({
  setup() {
    const route = useRoute();
    const articleId = route.params.id;
    
    const article = ref(null);
    const relatedArticles = ref([]);
    const loading = ref(true);
    const error = ref('');
    const likeCount = ref(Math.floor(Math.random() * 100)); // 模拟点赞数
    const isLiked = ref(false);
    
    const fetchArticle = async () => {
      if (!articleId) {
        error.value = '文章ID不能为空';
        loading.value = false;
        return;
      }
      
      loading.value = true;
      error.value = '';
      
      try {
        const response = await fetch(`http://localhost:9001/api/article/detail/${articleId}`);
        if (!response.ok) {
          throw new Error('获取文章详情失败');
        }
        
        const data = await response.json();
        article.value = data;
        
        // 加载完文章后获取相关文章
        fetchRelatedArticles();
      } catch (err) {
        console.error('获取文章详情时出错:', err);
        error.value = '加载文章失败: ' + err.message;
      } finally {
        loading.value = false;
      }
    };
    
    const fetchRelatedArticles = async () => {
      // 这里可以根据文章标签或内容相似度获取相关文章
      // 当前是简单模拟数据
      try {
        const response = await fetch('http://localhost:9001/api/article/list');
        if (response.ok) {
          const data = await response.json();
          let articlesArr = [];
          if (data && data.code === 1 && data.data && Array.isArray(data.data.list)) {
            articlesArr = data.data.list;
          } else if (Array.isArray(data)) {
            articlesArr = data;
          }
          // 过滤掉当前文章，最多显示3篇相关文章
          relatedArticles.value = articlesArr
            .filter(a => a.id !== article.value?.id)
            .slice(0, 3);
        }
      } catch (error) {
        console.error('获取相关文章失败:', error);
      }
    };
    
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    };
    
    const renderMarkdown = (markdownText) => {
      if (!markdownText) return '';
      
      // 配置Marked选项，提高渲染质量
      marked.setOptions({
        breaks: true, // 支持GitHub风格的换行
        gfm: true,    // 支持GitHub风格的Markdown
        headerIds: true,
        mangle: false
      });
      
      const html = marked(markdownText);
      return DOMPurify.sanitize(html); // 防止XSS攻击
    };
    
    const getTagArray = (tagsString) => {
      return tagsString ? tagsString.split(',').map(tag => tag.trim()) : [];
    };
    
    const getImageUrl = (path) => {
      if (!path) return '';
      if (/^https?:\/\//.test(path)) return path;
      if (!path.startsWith('/image')) {
        return '/image' + path.replace(/^\/static/, '');
      }
      return path;
    };
    
    const handleLike = () => {
      if (!isLiked.value) {
        likeCount.value++;
        isLiked.value = true;
      } else {
        likeCount.value--;
        isLiked.value = false;
      }
      
      // 这里可以添加实际的点赞API调用
      // await fetch('http://localhost:9001/api/article/like/' + articleId)
    };
    
    const handleShare = () => {
      // 模拟分享功能
      try {
        // 复制链接到剪贴板
        const url = window.location.href;
        navigator.clipboard.writeText(url)
          .then(() => {
            alert('链接已复制到剪贴板，可以分享给朋友了');
          })
          .catch(() => {
            // 剪贴板API失败的回退方案
            alert('请手动复制当前地址进行分享');
          });
      } catch (err) {
        console.error('分享失败:', err);
        alert('分享功能暂不可用，请手动复制地址');
      }
    };
    
    onMounted(fetchArticle);
    
    return {
      article,
      relatedArticles,
      loading,
      error,
      likeCount,
      isLiked,
      formatDate,
      renderMarkdown,
      getTagArray,
      getImageUrl,
      handleLike,
      handleShare
    };
  }
});
</script>

<style scoped>
.article-detail {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.article-header {
  margin-bottom: 30px;
}

.article-header h1 {
  font-size: 2.2em;
  margin-bottom: 15px;
  line-height: 1.3;
  color: #333;
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  color: #666;
  font-size: 14px;
  margin-bottom: 15px;
  align-items: center;
}

.article-meta span {
  display: flex;
  align-items: center;
  gap: 5px;
}

.article-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}

.tag {
  background-color: #e0e0e0;
  color: #333;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 14px;
  transition: all 0.2s;
}

.tag:hover {
  background-color: #d0d0d0;
}

.article-cover {
  margin-bottom: 30px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.article-cover img {
  width: 100%;
  max-height: 450px;
  object-fit: cover;
  display: block;
}

.article-body {
  margin-bottom: 40px;
  line-height: 1.8;
  font-size: 16px;
}

/* 必须添加:deep()以确保内部元素样式被应用 */
:deep(.markdown-body) {
  line-height: 1.8;
  color: #333;
}

:deep(.markdown-body h1) {
  font-size: 28px;
  margin-top: 40px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

:deep(.markdown-body h2) {
  font-size: 24px;
  margin-top: 30px;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.markdown-body h3) {
  font-size: 20px;
  margin-top: 25px;
  margin-bottom: 15px;
}

:deep(.markdown-body p) {
  margin-bottom: 20px;
  line-height: 1.8;
}

:deep(.markdown-body img) {
  max-width: 100%;
  border-radius: 6px;
  margin: 20px 0;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

:deep(.markdown-body a) {
  color: #2196F3;
  text-decoration: none;
  border-bottom: 1px solid transparent;
  transition: all 0.2s;
}

:deep(.markdown-body a:hover) {
  border-bottom-color: #2196F3;
}

:deep(.markdown-body pre) {
  background-color: #f6f8fa;
  border-radius: 6px;
  padding: 16px;
  overflow: auto;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 20px;
}

:deep(.markdown-body code) {
  background-color: #f6f8fa;
  padding: 3px 6px;
  border-radius: 3px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
  font-size: 90%;
}

:deep(.markdown-body blockquote) {
  border-left: 4px solid #4CAF50;
  padding: 0 16px;
  color: #555;
  margin: 0 0 20px;
  background-color: #f9f9f9;
  border-radius: 0 4px 4px 0;
}

:deep(.markdown-body ul),
:deep(.markdown-body ol) {
  padding-left: 25px;
  margin-bottom: 20px;
}

:deep(.markdown-body li) {
  margin-bottom: 8px;
}

.article-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 25px;
  border-top: 1px solid #eee;
  margin-top: 30px;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 15px;
  transition: all 0.3s;
  font-weight: 500;
}

.btn-like, .btn-share {
  background-color: #f0f0f0;
  color: #333;
}

.btn-like:hover, .btn-like.liked {
  background-color: #ffebee;
  color: #d32f2f;
}

.btn-share:hover {
  background-color: #e3f2fd;
  color: #1976d2;
}

.btn-back {
  background-color: #4CAF50;
  color: white;
  text-decoration: none;
}

.btn-back:hover {
  background-color: #388e3c;
}

.loading {
  padding: 40px 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  margin-bottom: 15px;
  border: 3px solid rgba(0,0,0,0.1);
  border-radius: 50%;
  border-top-color: #4CAF50;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error {
  background-color: #ffebee;
  color: #c62828;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}

/* 相关文章推荐 */
.related-articles {
  margin-top: 40px;
  padding-top: 25px;
  border-top: 1px solid #eee;
}

.related-articles h3 {
  margin-bottom: 15px;
  font-size: 20px;
  color: #333;
}

.related-list {
  list-style-type: none;
  padding: 0;
}

.related-list li {
  padding: 12px 0;
  border-bottom: 1px dashed #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.related-list a {
  color: #333;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.2s;
  flex: 1;
}

.related-list a:hover {
  color: #4CAF50;
}

.related-date {
  color: #888;
  font-size: 13px;
}

/* 图标样式 */
.icon-user::before {
  content: "👤";
}

.icon-calendar::before {
  content: "📅";
}

.icon-eye::before {
  content: "👁️";
}

.icon-heart::before {
  content: "❤️";
}

.icon-share::before {
  content: "📤";
}

@media (max-width: 768px) {
  .article-header h1 {
    font-size: 1.8em;
  }
  
  .article-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .article-actions {
    flex-direction: column;
    gap: 15px;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: center;
  }
  
  .btn-back {
    width: 100%;
    text-align: center;
  }
  
  .article-body {
    font-size: 15px;
  }
}
</style> 